package deployr.core;

import java.util.*;
import java.util.regex.*;

public class ScanChecksum {

	private final ScanListener listener;

	private final Pattern checksumAndPath = Pattern.compile("^(.*)  (.*)$");

	public ScanChecksum(ScanListener listener, String checksum) {
		this.listener = listener;
		scan(checksum);
	}

	private void md5Path(String md5, String path) {
		listener.discovered(path, md5);
	}

	private boolean needContinue(Scanner scanner) {
		return scanner.hasNext();
	}

	private String next(Scanner scanning) {
		String line = scanning.next();
		return line;
	}

	private void parse(String string) {
		Matcher md5AndPathMatcher = checksumAndPath.matcher(string);
		if (!md5AndPathMatcher.matches()) return;
		String checksum = md5AndPathMatcher.group(1);
		String path = md5AndPathMatcher.group(2);
		md5Path(checksum, path);
	}

	public void scan(String checksum) {
		Scanner scanning = startScanning(checksum);
		while (needContinue(scanning)) {
			parse(next(scanning));
		}
	}

	private Scanner startScanning(String checksum) {
		Scanner scannerCurr = new Scanner(checksum).useDelimiter("\n");
		return scannerCurr;
	}

}